//
//  YFBaseViewController.swift
//  YFSwiftWeibo
//
//  Created by tsaievan on 2017/8/24.
//  Copyright © 2017年 tsaievan. All rights reserved.
//

import UIKit

class YFBaseViewController: UIViewController {
    
    var visitorInfo: [String : String]?
    
    var tableView: UITableView?
    
    // 下拉刷新控件
    var refreshControl: YFRefreshControl?
    
    var isPullUp = false
    
    lazy var _navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.hm_screenWidth(), height: 64))
    
    lazy var _navItem: UINavigationItem = UINavigationItem()
    
    /// 重写title的set方法
    override var title: String? {
        didSet {
            _navItem.title = title
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: YFWeiBoUserLoginSuccessNotification), object: nil)
        setupUI()
        YFNetworkManager.shared.userLogon ? loadData() : ()
    }
}

extension YFBaseViewController {
    @objc fileprivate func login() {
        ///< 发通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: YFWeiboUserLoginNotification), object: nil)
    }
    
    @objc fileprivate func regist() {
        print("点击了注册按钮")
    }
    
    @objc fileprivate func loginSuccess(n: Notification) {
        print("登录成功: \(n)")
        /**
         * 以下这样写是不行的:
         * navigationItem.rightBarButtonItem = nil
         * navigationItem.leftBarButtonItem = nil
         * 因为我本身就没有设置navigationItem这个属性, 所以你再设置成nil也没用
         * 我设置的是自定义的属性,所以要用自定义的属性去置空
         */
        _navItem.leftBarButtonItem = nil
        _navItem.rightBarButtonItem = nil
        ///< 当这个view要显示时, 你先将它置为nil, 它就会继续走loadView, viewDidLoad等生命周期方法
        view = nil
        NotificationCenter.default.removeObserver(self)
    }
}

extension YFBaseViewController {
    fileprivate func setupUI() {
        view.backgroundColor = UIColor.hm_random()
        automaticallyAdjustsScrollViewInsets = false
        setupNavigationBar()
        YFNetworkManager.shared.userLogon ? setupTableView() : setupVistorView()
    }
    
    func loadData() {
        // 具体的由子类实现
        // 如果子类没有实现, 就停止刷新
        refreshControl?.endRefreshing()
    }
    
    func setupNavigationBar() {
        _navigationBar.backgroundColor = UIColor.hm_color(withHex: 0xf6f6f6)
        _navigationBar.items = [_navItem]
        _navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.darkGray]
        _navigationBar.tintColor = UIColor.orange
        view.addSubview(_navigationBar)
    }
    
    func setupTableView() {
        tableView = UITableView(frame: view.bounds, style: .plain)
        
        ///< 这里就是不使用懒加载的坏处, 如果下边的代码放到上面去, 那么tableView就为nil, 那么设置数据源和代理都不会有效果
        tableView?.contentInset = UIEdgeInsets(top: _navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        ///< 设置指示器的缩进, 这里的tableView可以强行解包, 因为这里的tableView是一定有值的
        tableView?.scrollIndicatorInsets = tableView!.contentInset
        tableView?.dataSource = self
        tableView?.delegate = self
        
        if let tableView = tableView {
            view.insertSubview(tableView, belowSubview: _navigationBar)
        }
        refreshControl = YFRefreshControl()
        if let refreshControl = refreshControl {
            tableView?.addSubview(refreshControl)
            refreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        }
    }
    
    func setupVistorView() {
        let visitorView = YFVisitorView(frame: view.bounds)
        visitorView.visitorInfo = visitorInfo
        visitorView.registButton?.addTarget(self, action: #selector(regist), for: .touchUpInside)
        visitorView.loginButton?.addTarget(self, action: #selector(login), for: .touchUpInside)
        _navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(regist))
        _navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
        view.insertSubview(visitorView, belowSubview: _navigationBar)
    }
}

// MARK: -UITableViewDataSource, UITableViewDelegate
extension YFBaseViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let row = indexPath.row
        let section = tableView.numberOfSections - 1
        if row < 0 || section < 0 {
            return
        }
        let count = tableView.numberOfRows(inSection: section)
        if row == count - 1 && !isPullUp {
            print("上拉刷新")
            
            // 把刷新的状态改了
            isPullUp = true
            
            // 刷新数据
            loadData()
        }
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 300
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
}

